from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework import mixins
from rest_framework import status

from meiduo_admin.serializers.users import AdminAuthSerializer
from meiduo_admin.serializers.users import UserInfoSerializer
from users.models import User


# POST /meiduo_admin/authorizations/
class AdminAuthView(APIView):

    def post(self, request):
        """
        管理员登录：
        ① 获取参数并进行校验(参数完整性、用户名和密码是否正确)
        ② 服务器需要生成jwt token
        ③ 返回响应数据，登录成功
        """
        # ① 获取参数并进行校验(参数完整性、用户名和密码是否正确)
        serializer = AdminAuthSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # ② 服务器需要生成jwt token
        serializer.save() # 调用序列化器类中的create方法

        # ③ 返回响应数据，登录成功
        return Response(serializer.data, status=status.HTTP_201_CREATED)


# GET /meiduo_admin/users/?keyword=<搜索关键字>
class UserInfoView(ListAPIView):
    permission_classes = [IsAdminUser]

    serializer_class = UserInfoSerializer
    # queryset = None

    def get_queryset(self):
        """重新父类中的get_queryset"""
        keyword = self.request.query_params.get('keyword')  # None

        if keyword:
            # 1.1 如果传递了keyword，查询用户名中含有keyword的普通用户的数据
            users = User.objects.filter(username__contains=keyword, is_staff=False)
        else:
            # 1.2 如果未传递keyword，查询所有的普通用户的数据
            users = User.objects.filter(is_staff=False)

        return users

    # @permission_required('users.view_user_api', raise_exception=True)
    @method_decorator(permission_required('users.view_user_api', raise_exception=True))
    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)
